import { ref, computed, onMounted } from 'vue'

// 全局主题状态
const isDarkMode = ref(false)

// 应用主题到 HTML 元素
const applyTheme = (dark: boolean) => {
  if (dark) {
    document.documentElement.classList.add('dark')
  } else {
    document.documentElement.classList.remove('dark')
  }
}

// 切换主题
const toggleTheme = () => {
  isDarkMode.value = !isDarkMode.value
  applyTheme(isDarkMode.value)
  localStorage.setItem('theme', isDarkMode.value ? 'dark' : 'light')
}

// 初始化主题
const initTheme = () => {
  const savedTheme = localStorage.getItem('theme')
  const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
  
  isDarkMode.value = savedTheme ? savedTheme === 'dark' : prefersDark
  applyTheme(isDarkMode.value)
}

// 主题相关的 CSS 类名
const themeClasses = computed(() => ({
  // 背景色
  bg: isDarkMode.value ? 'bg-gray-900' : 'bg-white',
  bgSecondary: isDarkMode.value ? 'bg-gray-800' : 'bg-gray-200',
  bgTertiary: isDarkMode.value ? 'bg-gray-700' : 'bg-gray-100',
  bgPrimary: isDarkMode.value ? 'bg-gray-900' : 'bg-gray-900',
  
  // 文字颜色
  text: isDarkMode.value ? 'text-white' : 'text-gray-900',
  textSecondary: isDarkMode.value ? 'text-gray-300' : 'text-gray-600',
  textMuted: isDarkMode.value ? 'text-gray-400' : 'text-gray-500',
  
  // 边框颜色
  border: isDarkMode.value ? 'border-gray-700' : 'border-gray-200',
  borderSecondary: isDarkMode.value ? 'border-gray-600' : 'border-gray-300',
  borderPrimary: isDarkMode.value ? 'border-gray-900' : 'border-gray-900',
  
  // 悬停效果
  hover: isDarkMode.value ? 'hover:bg-gray-700' : 'hover:bg-gray-100',
  
  // 按钮样式
  button: isDarkMode.value ? 'bg-gray-700 hover:bg-gray-600 text-white border-gray-600' : 'bg-white hover:bg-gray-50 text-gray-900 border-gray-300',
  
  // 输入框样式
  input: isDarkMode.value ? 'bg-gray-700 border-gray-600 text-white placeholder-gray-400' : 'bg-white border-gray-300 text-gray-900 placeholder-gray-500',
  
  // 卡片样式
  card: isDarkMode.value ? 'bg-gray-800 border-gray-700' : 'bg-white border-gray-200'
}))

export const useTheme = () => {
  return {
    isDarkMode,
    themeClasses,
    toggleTheme,
    initTheme
  }
}